<template>
  <div>
    <el-dialog
      :title="obj.isAdd ? '商品添加' : '商品编辑'"
      :visible.sync="obj.isTrue"
      width="40%"
      @close="cancel()" @opened="opened()">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="一级分类">
          <el-select v-model="form.first_cateid" placeholder="请选择一级分类" @change="changeOne()">
            <el-option label="请选择" :value="0" disabled></el-option>
            <el-option v-for="item in cateList" :key="item.id" :label="item.catename" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="二级分类">
          <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
            <el-option label="请选择" :value="0" disabled></el-option>
            <el-option v-for="item in secondCate" :key="item.id" :label="item.catename" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="form.goodsname"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="市场价格">
          <el-input v-model="form.market_price"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <div class="imgBox1">
            <h2>+</h2>
            <input type="file" @change="changeImg1" v-if="obj.isTrue" />
            <img :src="imgUrl" alt="" v-if="imgUrl" />
          </div>
        </el-form-item>
        <el-form-item label="商品规格">
          <el-select v-model="form.specsid" placeholder="请选择商品规格" @change="changeSpecs()">
            <el-option label="请选择" :value="0" disabled></el-option>
            <el-option v-for="item in specsList" :key="item.id" :label="item.specsname" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性">
          <el-select v-model="form.specsattr" multiple placeholder="请选择规格属性">
            <el-option label="请选择" :value="0" disabled></el-option>
            <el-option v-for="(item,index) in specsAttr" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品">
          <el-radio :label="1" v-model="form.isnew">是</el-radio>
          <el-radio :label="2" v-model="form.isnew">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖">
          <el-radio :label="1" v-model="form.ishot">是</el-radio>
          <el-radio :label="2" v-model="form.ishot">否</el-radio>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>
        <el-form-item label="商品描述">
          <div id="div1" v-if="obj.isTrue"></div>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="add()" v-if="obj.isAdd">添 加</el-button>
        <el-button type="primary" @click="enterEdit()" v-else>编 辑</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { cateList,goodsAdd,goodsInfo,goodsEdit} from "../../../request/api";
import { successAlert, warningAlert } from "../../../utils/alert";
import E from "wangeditor"
export default {
  props: ["obj"],
  components: {},
  data() {
    return {
      // 用来回显图片的
      imgUrl:"",
      form: {
        first_cateid:0,
        second_cateid:0,
        goodsname:"",
        price:"",
        market_price:"",
        img:"",
        description:"",
        specsid:"",
        specsattr:"",
        isnew:1,
        ishot:1,
        status:1
      },
      // 用来渲染二级分类的
      secondCate:[],
      // 用来渲染规格属性的
      specsAttr:[]
    };
  },
  computed: {
    ...mapGetters({
      cateList:"cate/list",
      specsList:"specs/list"
    }),
  },
  methods: {
    ...mapActions({
      asyncCateList:"cate/asyncList",
      asyncSpecsList:"specs/asyncList",
      asyncGoodsList: "goods/asyncList",
      asyncGoodsCount: "goods/asyncCount"
    }),
    // 遮罩层的打开动画结束时
    opened(){
      // 遮罩层的打开动画结束时之后再画富文本编辑器
      this.editor = new E('#div1')
      this.editor.create()

      // 在动画加载完毕之后设置内容
      this.editor.txt.html(this.form.description)
    },
    // 当一级分类发生变化
    changeOne(){
      // 最终效果：在二级分类下面根据一级分类选中的东西，渲染二级分类
      // 调接口，用你刚才选中的那一项的id来请求他下面的子分类
      cateList({pid:this.form.first_cateid}).then(res=>{
        // 给二级分类赋值
        this.secondCate = res.data.list
        // 清空之前选中的二级分类
        this.form.second_cateid = 0
      })
    },
    // 当商品规格发生变化
    changeSpecs(){
      // 最终效果：在规格属性下面根据商品规格选中的东西，渲染规格属性
      // 因为原有数据中包含了一级和二级，当一级发生变化在所有数据中查找那一项，然后将那一项的二级拿出来
      let obj = this.specsList.find(item=>{
        return item.id==this.form.specsid
      })
      // 给规格属性赋值，用来渲染下拉框
      this.specsAttr = obj.attrs
      // 清空之前选中的规格属性
      this.form.specsattr = ""
    },
    // 当图片那里发生变化
    changeImg1(e) {
      console.log(e);
      let file = e.target.files[0];
      // 验证图片大小限制
      // 单位换算   1024B=1KB   1024KB=1MB    1024MB=1GB
      if (file.size > 2 * 1024 * 1024) {
        warningAlert("图片大小超出限制");
        return;
      }
      // 验证图片类型
      let imgType = [
        "image/jpeg",
        "image/jpg",
        "image/webp",
        "image/gif",
        "image/png",
      ];
      if (!imgType.includes(file.type)) {
        warningAlert("请上传规定类型图片");
        return;
      }
      // 可以将图片信息转换成具体的图片
      this.imgUrl = URL.createObjectURL(file);
      // 给form中的img字段赋值
      this.form.img = file;
    },
    // 清空
    empty() {
      this.form = {
        first_cateid:0,
        second_cateid:0,
        goodsname:"",
        price:"",
        market_price:"",
        img:"",
        description:"",
        specsid:"",
        specsattr:"",
        isnew:1,
        ishot:1,
        status:1
      };
      this.secondCate = []
      this.specsAttr = []
      this.imgUrl = ""
    },
    // 点击取消
    cancel() {
      // 1、清空form中的数据
      this.empty();
      // 2、关闭遮罩层
      this.obj.isTrue = false;
    },
    // 点击添加
    add() {
      // 将规格属性转换成字符串数组
      // this.form.specsattr = JSON.stringify(this.form.specsattr)
      // 给form中的description赋值，值就是富文本编辑器的内容
      // this.form.description = this.editor.txt.html()
      let obj = {
        ...this.form,
        specsattr:JSON.stringify(this.form.specsattr),
        description:this.editor.txt.html()
      }

      goodsAdd(obj).then((res) => {
        if (res.data.code == 200) {
          // 添加成功
          successAlert(res.data.msg);
          // 清空form并关闭对话框
          this.cancel();
          // 刷新goods的列表数据
          this.asyncGoodsList();
          // 重新请求goods的列表总数
          this.asyncGoodsCount();
        } else {
          // 添加失败
          warningAlert(res.data.msg);
        }
      });
    },
    // 获取一条信息
    getOne(id) {
      goodsInfo({ id: id }).then((res) => {
        // 1、给form赋值
        this.form = res.data.list;
        // 2、先把里面的规格属性转成数组类型
        this.form.specsattr = JSON.parse(res.data.list.specsattr)
        // 3、根据刚刚获取到的一级分类，请求二级分类，渲染到页面中
        cateList({pid:this.form.first_cateid}).then(res=>{
          // 给二级分类赋值
          this.secondCate = res.data.list
        })
        // 4、给图片的路径设置地址，让图片显示出来
        this.imgUrl = this.$pre + this.form.img
        // 5、根据商品规格，查找对应的数据，渲染规格属性
        let obj = this.specsList.find(item=>{
          return item.id==this.form.specsid
        })
        // 给规格属性赋值，用来渲染下拉框
        this.specsAttr = obj.attrs
        // 6、给form设置id字段，因为后面确定编辑的时候需要用到
        this.form.id = id
      });
    },
    // 确定编辑
    enterEdit() {
      let obj = {
        ...this.form,
        specsattr:JSON.stringify(this.form.specsattr)
      }
      goodsEdit(obj).then((res) => {
        if (res.data.code == 200) {
          // 成功提示窗
          successAlert(res.data.msg);
          // 关闭当前遮罩层并清空数据
          this.cancel();
          // 重新请求列表数据
          this.asyncGoodsList();
        } else {
          // 失败提示窗
          warningAlert(res.data.msg);
        }
      });
    }
  },
  mounted() {
    // 页面一进来请求分类的数据
    this.asyncCateList()
    // 页面一进来请求商品规格的数据
    this.asyncSpecsList(true)
  },
};
</script>
<style scoped>
.imgBox1 {
  width: 150px;
  height: 150px;
  border: 1px dashed #ccc;
  position: relative;
}
.imgBox1 h2 {
  font-size: 50px;
  text-align: center;
  line-height: 150px;
  margin: 0;
}
.imgBox1 input {
  width: 150px;
  height: 150px;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  z-index: 3;
}
.imgBox1 img {
  width: 150px;
  height: 150px;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
}
</style>